package cn.com.callback

import cn.com.kh.LogToDB
import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.kh.getProperty;
import cn.com.kh.KHUtil;

import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject


/**
 *
 * @Title: waterOffIVR 智慧停水批次IVR播报信息接口--外部接口
 * @date 2021-03-05 10:28:00
 *
 */

public class waterOffIVR implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(waterOffIVR.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        String getMethod = request.getMethod();
        log.debug("IVR播报-getMethod:" + getMethod);
        long startTime = System.currentTimeMillis();

        String inData = "";
        String outData = "";
        String dataSourceID = "dataSource";

        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("IVR播报-原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("IVR播报-原始Post请求参数:" + inData);
        }

        try {
            // 调用处理信息
            JSONObject inObject = new JSONObject(inData);
            log.debug("IVR播报-处理前的Json：" + inObject.toString());
            def timestamp = KHUtil.GetJV(inObject, "timestamp");//时间戳
            def sign = KHUtil.GetJV(inObject, "sign");//密钥

            log.debug("IVR播报-解析信息-" + "	timestamp: " + timestamp + "	sign: " + sign);
            String reJson = null;
            long endTime = 0;

            String apiid = "waterOff";
            String apikey = "55bd38420d354822bdb789284fac4ab3";
            String signfront = "";
            String signafter = ""

            signfront = "apiid" + "=" + apiid + "&" + "apikey" + "=" + apikey + "&" + "timestamp" + "=" + timestamp;
            log.debug("IVR播报-sign加密MD5前：" + signfront);
            signafter = Util.getMD5Str(signfront);
            log.debug("IVR播报-sign加密MD5后：" + signafter);

            if (!sign.equals(signafter)) {
                log.debug("IVR播报-signafter不存在");
                endTime = System.currentTimeMillis();
                outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(sign签名错误),调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
            } else {

                String wateroffsmsguid = KHUtil.GetJV(inObject, "wateroffsmsguid");
                String wateroffsmsname = KHUtil.GetJV(inObject, "wateroffsmsname");
                String typeid = KHUtil.GetJV(inObject, "typeid");
                String content = KHUtil.GetJV(inObject, "content");
                String waterontime = KHUtil.GetJV(inObject, "waterontime");
                String person = KHUtil.GetJV(inObject, "person");
                String phone = KHUtil.GetJV(inObject, "phone");

                //非空校验
                // isNull(wateroffsmsguid)||isNull(wateroffsmsname)||isNull(typeid)||isNull(content)||isNull(waterontime)
                String dealMessage = "";
                if (KHUtil.isNull(content)) {
                    dealMessage = KHUtil.isNullMSG("wateroffsmsguid", wateroffsmsguid) + KHUtil.isNullMSG("wateroffsmsname", wateroffsmsname) + KHUtil.isNullMSG("typeid", typeid);
                } else {
                    dealMessage = KHUtil.isNullMSG("wateroffsmsguid", wateroffsmsguid) + KHUtil.isNullMSG("wateroffsmsname", wateroffsmsname) + KHUtil.isNullMSG("typeid", typeid) + KHUtil.isNullMSG("waterontime", waterontime) + KHUtil.isNullMSG("person", person) + KHUtil.isNullMSG("phone", phone);
                }

                if (!KHUtil.isNull(dealMessage)) {
                    endTime = System.currentTimeMillis();
                    outData = "{\"resultcode\":\"0\",\"resultmessage\":\"批次号:" + wateroffsmsguid + "-调用参数非空校验异常:" + dealMessage + "，调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                } else {
                    log.debug("IVR播报-入参：wateroffsmsguid" + wateroffsmsguid + ",	typeid:" + typeid + ",	content:" + content + ",	waterontime:" + waterontime);

                    //新增动态语音
                    outData = SMSIVRAdd(eliteBean, wateroffsmsguid, wateroffsmsname, typeid, content, waterontime, person, phone, dataSourceID);
                }
            }
        } catch (Exception e) {
            log.error("IVR播报-动态语音接口处理异常" + e.getMessage());
            // 失败返回
            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "智慧停水[IVR]", "waterOffIVR", inData, outData, (System.currentTimeMillis() - startTime).toString(), getMethod);
        }

        log.debug("IVR播报-动态语音数据接入处理完成返回结果:" + outData);

        return outData;
    }

    // 动态语音
    public static String SMSIVRAdd(EliteBean eliteBean, String wateroffsmsguid, String wateroffsmsname, String typeid, String content, String waterontime, String person, String phone, String dataSourceID) {

        long startTime = System.currentTimeMillis();
        log.debug("IVR播报-动态语音处理开始时间:" + startTime);

        long endTime = System.currentTimeMillis();

        String personphone = person + "	" + phone;
        String reJson = null;
        try {
            //查询现有当前动态语音播报是否存在
            def getSelectSQL = eliteBean.chaxun_sql("select count(*) as count from sysc_template1 where wateroffsmsguid= '" + wateroffsmsguid + "' ", "dataSource");
            def count = 0;
            if (getSelectSQL.size() > 0) {
                count = getSelectSQL.get(0).get("count");
                if (count > 0) {//是否存在
                    def getSelecttemplate_idSQL = eliteBean.chaxun_sql("Select Template_Id As template_id From Sysc_Template1 Where Wateroffsmsguid = '" + wateroffsmsguid + "'", "dataSource");
                    String template_id = "";
                    if (getSelecttemplate_idSQL.size() > 0) {
                        template_id = getSelecttemplate_idSQL.get(0).get("template_id");
                    }

                    String[] abandondata = new String[3];
                    //将之前的批次更新为废弃
                    abandondata[0] = "Delete Sysc_Template1 Where 1 = 1 And Wateroffsmsguid = '" + wateroffsmsguid + "'";
                    abandondata[1] = "Delete Prompt_Content Where 1 = 1 And Prompt_Guid = '" + template_id + "'";
                    abandondata[2] = "Insert Into Wateroffivr_His (Template_Id, Template_Type, Template_Desc, Createdate, Wateroffsmsguid, Wateroffsmsname, Waterontime, Changetime, Changestaff, Changedo) Values ('" + template_id + "', '" + typeid + "', '" + content + "', GETDATE(),'" + wateroffsmsguid + "','" + wateroffsmsname + "','" + waterontime + "',getdate(),'SELITE','删除')";

                    log.debug("IVR播报-当前动态语音已经存在执行果SQL:" + abandondata.toString());
                    def abandondataresult = eliteBean.updateBatch(abandondata, dataSourceID);
                    log.debug("IVR播报-当前动态语音已经存在执行结果SQL结果:" + abandondataresult.toString());
                }
            }

            if (!KHUtil.isNull(content)) {
                String template_id = UUID.randomUUID().toString();
                String[] data = new String[5];

                data[0] = "Delete Sysc_Template1 Where 1 = 1 And Wateroffsmsguid Is Not Null And Waterontime <= Getdate()";
                data[1] = "Insert Into Sysc_Template1 (Template_Id, Template_Type, Template_Desc, Createdate, Wateroffsmsguid, Wateroffsmsname, Waterontime) Values ('" + template_id + "', '" + typeid + "', '" + content + "', GETDATE(),'" + wateroffsmsguid + "','" + wateroffsmsname + "','" + waterontime + "')";
                data[2] = "Insert Into Wateroffivr_His (Template_Id, Template_Type, Template_Desc, Createdate, Wateroffsmsguid, Wateroffsmsname, Waterontime, Changetime, Changestaff, Changedo) Values ('" + template_id + "', '" + typeid + "', '" + content + "', GETDATE(),'" + wateroffsmsguid + "','" + wateroffsmsname + "','" + waterontime + "',getdate(),'SELITE','新增')";
                data[3] = "Insert Into Prompt_Content (Prompt_Guid, Prompt_Matter_Id, Content, Priority, Createdate, Area, Createby, Creategroup, Modifytime, Leading_Official, Area_Type) Values ('" + template_id + "','02C0D6','" + content + "','86876F',getdate(),'" + typeid + "','SELITE','SYSTEM',getdate(),'" + personphone + "',CASE '" + typeid + "' WHEN 'JT0001' THEN '475AE8F5-8C60-0947-96D6-D4999CE07DF4' WHEN 'NA0001' THEN '475AE8F5-8C60-0947-96D6-D4999CE07DF4' WHEN 'PD0001' THEN '475AE8F5-8C60-0947-96D6-D4999CE07DF4' WHEN 'LH0001' THEN '475AE8F5-8C60-0947-96D6-D4999CE07DF4' WHEN 'BA0001' THEN '74BCB8CD-D886-7B4D-BE0E-AAECE71FA6DE' WHEN 'LG0001' THEN '95ED5385-7379-1041-919A-BDF10A1CB5DC' WHEN 'GM0001' THEN 'ED48B3EA-347F-684F-99A3-9C0BA66B744F' END)";
                data[4] = "Insert Into History_Prompt_Content (Prompt_Guid, Prompt_Matter_Id, Content, Priority, Createdate, Area, Steps, Changestaffid, Changedate, Area_Type) Values ('" + template_id + "','02C0D6','" + content + "','86876F',getdate(),'" + typeid + "','新增','SELITE',getdate(),CASE '" + typeid + "' WHEN 'JT0001' THEN '475AE8F5-8C60-0947-96D6-D4999CE07DF4' WHEN 'NA0001' THEN '475AE8F5-8C60-0947-96D6-D4999CE07DF4' WHEN 'PD0001' THEN '475AE8F5-8C60-0947-96D6-D4999CE07DF4' WHEN 'LH0001' THEN '475AE8F5-8C60-0947-96D6-D4999CE07DF4' WHEN 'BA0001' THEN '74BCB8CD-D886-7B4D-BE0E-AAECE71FA6DE' WHEN 'LG0001' THEN '95ED5385-7379-1041-919A-BDF10A1CB5DC' WHEN 'GM0001' THEN 'ED48B3EA-347F-684F-99A3-9C0BA66B744F' END)";

                log.debug("IVR播报-当前动态语音批次新建SQL:" + data.toString());
                def dataresult = eliteBean.updateBatch(data, dataSourceID);
                log.debug("IVR播报-当前动态语音批次新建结果SQL结果:" + dataresult.toString());
            }

            //调用存储过程处理IVR 停水通知 播报内容
            log.debug("IVR播报-SMS_Link调用存储过程处理停水通知数据...");
            def procedure = "{call Dbo.SMS_Link(?,?)}";
            def inputMap = new String[1];
            inputMap[0] = "SMS_Link";

            log.debug("IVR播报-SMS_Link调用存储过程处理SQL:" + procedure);
            def reSult = eliteBean.executeWithReturn(procedure, inputMap, 'dataSource');
            log.debug("IVR播报-SMS_Link调用存储过程处理返回:" + reSult);

            // 包装拼接返回JSONObject
            reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffsmsguid + "-处理完成,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\",\"data\":[]}";


        } catch (JSONException e) {
            reJson = "{\"resultcode\":\"4\",\"resultmessage\":\"批次号:" + wateroffsmsguid + "-处理失败(" + e.getMessage() + "),调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
        }

        return reJson;
    }

}
